package com.syher.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

import static java.nio.file.StandardWatchEventKinds.*;

/**
 * @author shenyuhang
 * @date 2018/07/25.
 **/
public class FileWatcher {

    WatchService service;
    String path;

    public FileWatcher(String path) {
        try {
            this.path = path;
            this.service = FileSystems.getDefault().newWatchService();
            Paths.get(path).register(service, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
            List<Path> pathList = Files.list(Paths.get(path)).filter(Files::isDirectory).collect(Collectors.toList());
            for (Path p : pathList) {
                p.register(service, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void handleEvents() {
        try {
            while (true) {
                WatchKey key = service.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    //事件可能lost or discarded
                    if (kind == OVERFLOW) {
                        continue;
                    }

                    WatchEvent<Path> e = (WatchEvent<Path>) event;
                    Path fileName = e.context();
                    String filePath = String.join(File.separator, path, fileName.toString());
                    System.out.printf("Event %s has happened,which fileName is %s%n"
                            , kind.name(), filePath);

                }
                if (!key.reset()) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileWatcher("G:\\syhenian\\watcher").handleEvents();
    }
}
